package com.shouhuobao.visit;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Message;
import android.text.InputFilter;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ZoomControls;

import com.baidu.location.BDLocation;
import com.baidu.location.Poi;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.Overlay;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.collectplus.express.BaseActivity2;
import com.collectplus.express.R;
import com.collectplus.express.logic.AppCache;
import com.collectplus.express.logic.AppConfig;
import com.collectplus.express.logic.AppHttp;
import com.collectplus.express.logic.AppResult;
import com.collectplus.express.logic.JSON;
import com.collectplus.express.logic.MsgID;
import com.collectplus.express.model.Const;
import com.collectplus.express.model.CourierBean;
import com.collectplus.express.model.ReceiverBean;
import com.collectplus.express.model.ServicePointBean;
import com.collectplus.express.model.UserBean;
import com.collectplus.express.model.VisitDoorBackBean;
import com.collectplus.express.model.VisitDoorBean;
import com.collectplus.express.self.SelfOrderSubmitActivity;
import com.collectplus.express.tools.LengthInputFilter;
import com.collectplus.express.tools.TextWatcherExt;
import com.shouhuobao.bhi.loc.BaiduLocationService;

import java.util.ArrayList;
import java.util.List;

import droid.frame.utils.lang.Str;
import droid.frame.view.InputFilterExt;

/**
 * Created by joker on 2017/12/13.
 * 上门取件activity
 */
public class VisitHomeActivity extends BaseActivity2 implements View.OnClickListener {

    private MapView mMapView;
    private BaiduMap mBaiduMap;
    private GeoCoder mGeoCoder = null;
    private EditText mPhoneET;//手机号码
    private EditText mAddressET;//详细地址
    private TextView mAddressNameTV;//例如雍和大厦
    private TextView mDistrictNameTV;//区域名字加街道名字
    private TextView mVisitDoorTitleTV;//上门费用标题
    private TextView mPeriodTV;//上门夜间，高峰期
    private TextView mPriceTV;//上门费用
    private TextView mDiscountTitleTV;//优惠标题
    private TextView mArriverMinuteTV;//多长时间到达

    private View mMyLocationMarkerView = null;
    private ArrayList<Marker> mMarks = new ArrayList<Marker>();
    private ArrayList<CourierBean> items = new ArrayList<>();

    private double latitude;
    private double longitude;
    private String province;//省
    private String city;//市
    private String district;//区域

    private ReceiverBean cacheReceiver = null;
    private VisitDoorBean visitDoorBean = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        cacheReceiver = AppCache.getParcelNew();
        if (null == cacheReceiver) {
            cacheReceiver = new ReceiverBean(Const.ParcelType.visitToHome);
            AppCache.setParcelNew(cacheReceiver);
        } else {
            cacheReceiver.setType(Const.ParcelType.visitToHome);
            AppCache.setParcelNew(cacheReceiver);
        }
        if (null == cacheReceiver.getServicePoint()) {
            ServicePointBean bean = new ServicePointBean();
            bean.setType(Const.ParcelType.visitToHome);
            bean.setPayType(1);
            cacheReceiver.setServicePoint(bean);
        } else {
            cacheReceiver.getServicePoint().setType(Const.ParcelType.visitToHome);
            cacheReceiver.getServicePoint().setPayType(1);
        }
        visitDoorBean = cacheReceiver.getVisitDoorBean();
        if (null == visitDoorBean) {
            visitDoorBean = new VisitDoorBean();
        }
        super.onCreate(savedInstanceState);
        showLoadingDialog("正在定位");
        Intent intent = new Intent();
        intent.setClass(getContext(), BaiduLocationService.class);
        intent.putExtra("msgId", MsgID.get_visit_location);
        startService(intent);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        mMapView.onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void findViewById() {
        setContentView(R.layout.activity_visit_home);
        super.findViewById();
        getAppTitle().setCommonTitle("上门取件");
        mAddressNameTV = (TextView) findViewById(R.id.address_name_tv);
        mDistrictNameTV = (TextView) findViewById(R.id.district_name_tv);
        findViewById(R.id.select_location_tv).setOnClickListener(this);
        findViewById(R.id.re_location_iv).setOnClickListener(this);
        final TextView addressTitleTV = (TextView) findViewById(R.id.address_title_tv);
        mAddressET = (EditText) findViewById(R.id.address_et);
        final TextView phoneTitleTV = (TextView) findViewById(R.id.phone_title_tv);
        mPhoneET = (EditText) findViewById(R.id.phone_et);
        mAddressET.setFilters(new InputFilter[]{new InputFilterExt(0), new LengthInputFilter(mAddressET, 50)});
        mAddressET.addTextChangedListener(new TextWatcherExt() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (isEmpty(s)) {
                    addressTitleTV.setTextColor(getResources().getColor(R.color.app_font_2));
                } else {
                    addressTitleTV.setTextColor(getResources().getColor(R.color.app_font_1));
                }
            }
        });
        mPhoneET.addTextChangedListener(new droid.frame.view.TextWatcherExt(1) {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 可以修改手机号
                if (s.length() == 13) {
                    phoneTitleTV.setTextColor(getResources().getColor(R.color.app_font_1));
                } else {
                    phoneTitleTV.setTextColor(getResources().getColor(R.color.app_font_2));
                }
            }
        });
        mVisitDoorTitleTV = (TextView) findViewById(R.id.visit_door_tv);
        mPeriodTV = (TextView) findViewById(R.id.period_tv);
        mPriceTV = (TextView) findViewById(R.id.price_tv);
        mDiscountTitleTV = (TextView) findViewById(R.id.discount_tv);
        findViewById(R.id.confirm_bt).setOnClickListener(this);
        UserBean userBean = AppCache.getUser();
        mPhoneET.setText(userBean.getPhone());
        mMyLocationMarkerView = LayoutInflater.from(getContext()).inflate(R.layout.layout_visit_send_tip, null, false);
        initMapView();
        mArriverMinuteTV = (TextView) mMyLocationMarkerView.findViewById(R.id.arriver_time_tv);
    }

    private void initMapView() {
        // 地图初始化
        mMapView = (MapView) findViewById(R.id.bmapView);
        mMapView.showZoomControls(false);//隐藏缩放按钮
        mMapView.showScaleControl(false);//隐藏比例尺
        int count = mMapView.getChildCount();
        for (int i = 0; i < count; i++) {
            View child = mMapView.getChildAt(i);
            // 隐藏缩放按键 ZoomControl
            if (child instanceof ImageView || child instanceof ZoomControls) {
                child.setVisibility(View.INVISIBLE);
            }
        }
        mBaiduMap = mMapView.getMap();
        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);

        MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(15.0f);
        mBaiduMap.setMapStatus(msu);
        mGeoCoder = GeoCoder.newInstance();
        setMyMapStatusChangeListener(true);
    }

    private void setMyMapStatusChangeListener(boolean isNull) {
        if (isNull) {
            mBaiduMap.setOnMapStatusChangeListener(null);
        } else {
            mGeoCoder.setOnGetGeoCodeResultListener(geoListener);
            getHandler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    mBaiduMap.setOnMapStatusChangeListener(listener);
                }
            }, 1000);
        }
    }

    /**
     * 监听百度地图变化
     */
    private BaiduMap.OnMapStatusChangeListener listener = new BaiduMap.OnMapStatusChangeListener() {

        @Override
        public void onMapStatusChangeStart(MapStatus status) {
        }

        @Override
        public void onMapStatusChangeStart(MapStatus mapStatus, int i) {

        }

        @Override
        public void onMapStatusChangeFinish(MapStatus status) {
            if ((int) status.bound.southwest.latitude > 1) {
                // mapview 中心点
                latitude = status.target.latitude;
                longitude = status.target.longitude;
                mGeoCoder.reverseGeoCode(new ReverseGeoCodeOption().location(new LatLng(latitude, longitude)));
                items.clear();
                items.add(new CourierBean(longitude, latitude));
                addMarkToMap();
                queryCourierInfo(0, latitude, longitude);
            }
        }

        @Override
        public void onMapStatusChange(MapStatus status) {

        }
    };

    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
            //重新定位选择
            case R.id.select_location_tv:
                intent.setClass(getContext(), VisitAddressActivity.class);
                intent.putExtra("lat", latitude);
                intent.putExtra("lng", longitude);
                intent.putExtra("city", city);
                startActivityForResult(intent, 1200);
                break;
            //地图上重新定位
            case R.id.re_location_iv:
                showLoadingDialog("正在定位");
                intent.setClass(getContext(), BaiduLocationService.class);
                intent.putExtra("msgId", MsgID.get_visit_location);
                startService(intent);
                break;
            //确认选择
            case R.id.confirm_bt:
                String address = mAddressET.getText().toString();
                if (isNotEmpty(address)) {
//                    queryCourierInfo(1, latitude, longitude);
                    visitDoorBean.setBuildName(mAddressNameTV.getText().toString());
                    visitDoorBean.setLatitude(latitude);
                    visitDoorBean.setLongitude(longitude);
                    visitDoorBean.setProvince(province);
                    visitDoorBean.setCity(city);
                    visitDoorBean.setDistrict(district);
                    visitDoorBean.setAddress(mDistrictNameTV.getText().toString());
                    visitDoorBean.setAddressDesc(Str.filter(mAddressET.getText().toString()));
                    visitDoorBean.setPhone(mPhoneET.getText().toString().replace(" ", ""));
                    cacheReceiver.setVisitDoorBean(visitDoorBean);
                    AppCache.setParcelNew(cacheReceiver);
                    startActivity(SelfOrderSubmitActivity.class);
                } else {
                    showToast("请填写楼层门牌");
                }

                break;
        }
    }

    /**
     * 根据经纬度查询附近火箭侠信息和上门取件的信息
     *
     * @param type 0 根据经纬度查询附近的火箭侠信息和上门取件的相关信息
     *             1  上门取件界面点击确认选择判断附近是否有可用火箭侠
     */
    private void queryCourierInfo(int type, double lat, double lng) {
        showLoadingDialog("查询中");
        AppHttp.getInstance().queryCourierInfoByLocation(type, lng, lat);
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case MsgID.get_visit_location:
                cancelLoadingDialog();
                final BDLocation loc = (BDLocation) msg.obj;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (loc == null) {
                            cancelLoadingDialog();
                            showToast("定位失败");
                        } else {
                            String currentCityName = loc.getCity();
                            if (isNotEmpty(currentCityName)) {
                                List<Poi> list = loc.getPoiList();
                                if (list != null && list.size() > 0) {
                                    mAddressNameTV.setText(list.get(0).getName());
                                } else {
                                    showToast("获取当前位置信息失败");
                                }
                                if (AppConfig.isOtherCity != 0) {
                                    mDistrictNameTV.setText(AppConfig.getDistrict());
                                    province = AppConfig.getProvince();
                                    city = AppConfig.getCityName();
                                    district = AppConfig.getDistrict();
                                } else {
                                    mDistrictNameTV.setText(loc.getDistrict() + loc.getStreet());
                                    province = loc.getProvince();
                                    city = loc.getCity();
                                    district = loc.getDistrict();
                                }
                                latitude = loc.getLatitude();
                                longitude = loc.getLongitude();
                                items.add(0, new CourierBean(loc.getLongitude(), loc.getLatitude()));
                                MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(new LatLng(loc.getLatitude(), loc.getLongitude()));
                                mBaiduMap.animateMapStatus(u);
                                addMarkToMap();
                                setMyMapStatusChangeListener(false);
                                queryCourierInfo(0, loc.getLatitude(), loc.getLongitude());
                            } else {
                                showToast("定位失败");
                            }
                        }
                    }
                });
                return false;
            //根据经纬度查询附近上门信息
            case MsgID.query_courier_info_by_location:
                cancelLoadingDialog();
                final AppResult<VisitDoorBackBean> appResult = JSON.parser(msg.obj, VisitDoorBackBean.class);
                if (appResult.isSuccess()) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            VisitDoorBackBean backBean = appResult.getResult();
                            if (isEmpty(backBean.getType())) {
                                mPeriodTV.setVisibility(View.GONE);
                                mVisitDoorTitleTV.setText("上门费：");
                            } else {
                                mPeriodTV.setVisibility(View.VISIBLE);
                                mVisitDoorTitleTV.setText("上门费");
                                mPeriodTV.setText("(" + backBean.getType() + ")：");
                            }
                            //判断是否进行优惠
                            if (1 == backBean.getDiscountType()) {
                                mPriceTV.getPaint().setAntiAlias(true);//抗锯齿
                                mPriceTV.setPaintFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
                                mPriceTV.setText("￥" + backBean.getPrice());
                            } else {
                                mPriceTV.setText("￥" + backBean.getPrice());
                            }
                            //判断是否显示优惠信息
                            if (isEmpty(backBean.getDiscount())) {
                                mDiscountTitleTV.setVisibility(View.GONE);
                            } else {
                                mDiscountTitleTV.setVisibility(View.VISIBLE);
                                mDiscountTitleTV.setText("（" + backBean.getDiscount() + "）");

                            }
                            //判断附近是否有火箭侠
                            if (backBean.getList() != null && backBean.getList().size() > 0) {
                                mArriverMinuteTV.setText(backBean.getList().get(0).getMinute());
                                items.addAll(backBean.getList());
                            } else {
                                if (items.size() > 0) {
                                    CourierBean bean = items.get(0);
                                    items.clear();
                                    items.add(bean);
                                }
                            }
                            addMarkToMap();
                        }
                    });
                } else {
                    showToast(appResult.getMessage());
                }
                return true;
//            case MsgID.is_submit_order_by_location:
//                cancelLoadingDialog();
//                final AppResult<?> result = JSON.parser(msg.obj);
//                if (result.isSuccess()) {
//                    runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            boolean resultFlag = (Boolean) result.getResult();
//                            if (resultFlag) {
//                                visitDoorBean.setBuildName(mAddressNameTV.getText().toString());
//                                visitDoorBean.setLatitude(latitude);
//                                visitDoorBean.setLongitude(longitude);
//                                visitDoorBean.setProvince(province);
//                                visitDoorBean.setCity(city);
//                                visitDoorBean.setDistrict(district);
//                                visitDoorBean.setAddress(mDistrictNameTV.getText().toString());
//                                visitDoorBean.setAddressDesc(Str.filter(mAddressET.getText().toString()));
//                                visitDoorBean.setPhone(mPhoneET.getText().toString().replace(" ", ""));
//                                cacheReceiver.setVisitDoorBean(visitDoorBean);
//                                AppCache.setParcelNew(cacheReceiver);
//                                startActivity(SelfOrderSubmitActivity.class);
//                            } else {
////                                DialogMgr.showSubmitOrderTipsDialog(getContext());
//                                DialogMgr.notNearByCourierTips(getContext());
//                            }
//                        }
//                    });
//                } else {
//                    showToast(result.getMessage());
//                }
//                return true;
            default:
                return super.handleMessage(msg);
        }
    }

    /**
     * 用于添加火箭侠的位置和我的位置
     */
    private void addMarkToMap() {
        if (mMarks.size() > 0) {
            mMapView.getMap().clear();
            mMarks.clear();
        }

        for (int i = 0; i < items.size(); i++) {
            makeMarker(i);
        }
    }

    /**
     * 添加地图上marker
     *
     * @param position
     * @return
     */
    public Marker makeMarker(int position) {
        CourierBean item = items.get(position);
        LatLng llB = new LatLng(item.getLatitude(), item.getLongitude());
        OverlayOptions ooB = null;
        BitmapDescriptor bitmap = null;
        if (position == 0) {//第一条数据用来记录我的目前位置
            bitmap = BitmapDescriptorFactory
                    .fromView(mMyLocationMarkerView);
            ooB = new MarkerOptions().position(llB).icon(bitmap).zIndex(10).draggable(true);
        } else {
            bitmap = BitmapDescriptorFactory
                    .fromResource(R.drawable.visit_courier_location_icon);
            ooB = new MarkerOptions().position(llB).icon(bitmap).zIndex(9).draggable(true);
        }
        Overlay overlay = mMapView.getMap().addOverlay(ooB);
        Marker marker = (Marker) (overlay);
        Bundle bundle = new Bundle();
        bundle.putInt("point", position);
        marker.setExtraInfo(bundle);
        mMarks.add(marker);
        return marker;
    }

    /**
     * 搜索结果回调
     */
    OnGetGeoCoderResultListener geoListener = new OnGetGeoCoderResultListener() {
        @Override
        public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {
        }

        @Override
        public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {
            if (reverseGeoCodeResult == null) {
                showToast("获取附近位置信息失败");
                return;
            }
            if (null != reverseGeoCodeResult.getPoiList() && reverseGeoCodeResult.getPoiList().size() > 0) {
                mAddressNameTV.setText(reverseGeoCodeResult.getPoiList().get(0).name);
            }
            ReverseGeoCodeResult.AddressComponent addressComponent = reverseGeoCodeResult.getAddressDetail();
            LatLng latLng = reverseGeoCodeResult.getLocation();
            if (addressComponent != null && latLng != null) {
                province = addressComponent.province;
                city = addressComponent.city;
                district = addressComponent.district;
                latitude = latLng.latitude;
                longitude = latLng.longitude;
                mDistrictNameTV.setText(addressComponent.district + addressComponent.street);
            }
        }
    };

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK && 1200 == requestCode) {
            VisitDoorBean item = (VisitDoorBean) data.getSerializableExtra("item");
            if (item != null) {
                //这里必须要设置，负责地图发生变化会进行监听，然后会调用反搜索的数据
                setMyMapStatusChangeListener(true);
                mAddressNameTV.setText(item.getBuildName());
                mDistrictNameTV.setText(item.getAddress());
                if (isNotEmpty(item.getPhone())) {
                    mPhoneET.setText(item.getPhone());
                }
                latitude = item.getLatitude();
                longitude = item.getLongitude();
                province = item.getProvince();
                city = item.getCity();
                district = item.getDistrict();
                items.clear();
                items.add(new CourierBean(longitude, latitude));
                MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(new LatLng(latitude, longitude));
                mBaiduMap.animateMapStatus(u);
                addMarkToMap();
                queryCourierInfo(0, latitude, longitude);
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    protected void onDestroy() {
        if (mMapView != null) {
            mMapView.onDestroy();
            mMapView = null;
            mMarks.clear();
        }
        if (mGeoCoder != null) {
            mGeoCoder.destroy();
        }
        setMyMapStatusChangeListener(true);
        super.onDestroy();
//        if (null != cacheReceiver) {
//            cacheReceiver.setType(Const.ParcelType.bagToHome);
//            cacheReceiver.setVisitDoorBean(null);
//            AppCache.setParcelNew(cacheReceiver);
//        }
    }
}
